<<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
<<<<<<< HEAD
In [236]:
=======
In [36]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# imports

import random
random.seed(8675309)

import os
os.environ['KERAS_BACKEND'] = 'tensorflow'

import cv2 
from glob import glob
<<<<<<< HEAD
from time import time
from tqdm import tqdm, tqdm_notebook
import urllib
=======
from tqdm import tqdm, tqdm_notebook
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt  
%matplotlib inline  

<<<<<<< HEAD
from sklearn.datasets import load_files 
from sklearn.utils import shuffle
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.decomposition import PCA
from sklearn.svm import SVC

=======
from sklearn.datasets import load_files       
from sklearn.decomposition import PCA
 
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
from keras.utils import np_utils
from keras.preprocessing import image   
from keras.applications.resnet50 import preprocess_input, decode_predictions
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint  

from PIL import ImageFile   
<<<<<<< HEAD
In [228]:
# utility function to plot an image
def show_image(img_path, title='default'):
    img = cv2.imread(img_path)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)
    if title is not None:
        if title == 'default':
            title = img_path.rsplit(os.sep, 1)[-1]
        plt.title(title)
    plt.show()   
In [2]:
=======
In [31]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

<<<<<<< HEAD
In [5]:
=======
In [32]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
There are 13233 total human images.
<<<<<<< HEAD
In [6]:
=======
In [4]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# show randomly some pictures...
n_fig2plot = 5
plt.figure(figsize=(20, 5))
for i, hf in enumerate(np.random.choice(human_files, n_fig2plot)):
    plt.subplot(1, n_fig2plot, i+1)
    img = cv2.imread(hf)
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(cv_rgb)
    plt.title(hf.split(os.sep)[1])

plt.show()
<<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

<<<<<<< HEAD
In [7]:
=======
In [5]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
Number of faces detected: 1
<<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

<<<<<<< HEAD
In [8]:
=======
In [6]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
  • percentage of the first 100 images in human_files having a detected human face: 98%
  • percentage of the first 100 images in dog_files having a detected human face: 11%
<<<<<<< HEAD
In [9]:
=======
In [8]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
def assessHumanFaces(files):
    n_files = len(files)
    results = np.zeros(n_files)
<<<<<<< HEAD
    for i, f in enumerate(tqdm_notebook(files)):
=======
    for i, f in enumerate(files):
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
        if face_detector(f):
            results[i] = 1
            
    return results

print('Assessing percentage of the first 100 images in human_files having a detected human face...')    
%time human_results = assessHumanFaces(human_files_short) 
print("human faces detected: {} %".format(np.sum(human_results)))
<<<<<<< HEAD
Assessing percentage of the first 100 images in human_files having a detected human face...
CPU times: user 7.59 s, sys: 36.3 ms, total: 7.63 s
Wall time: 2.15 s
=======

Assessing percentage of the first 100 images in human_files having a detected human face...
CPU times: user 7.33 s, sys: 17.1 ms, total: 7.35 s
Wall time: 2.03 s
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
human faces detected: 98.0 %
<<<<<<< HEAD
In [10]:
=======
In [9]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
print('No human face detected in {} pictures:'.format(int(len(human_results) - np.sum(human_results))))

plt.figure(figsize=(20, 5))

plt_idx = 0
<<<<<<< HEAD
for i, hm in enumerate(tqdm_notebook(human_results)):
=======
for i, hm in enumerate(human_results):
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    if not hm:
        plt_idx += 1
        plt.subplot(1, 3, plt_idx)
        img = cv2.imread(human_files_short[i])
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)
        plt.title(human_files_short[i].split(os.sep)[1])

plt.show()  
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
No human face detected in 2 pictures:
<<<<<<< HEAD

=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [11]:
=======
In [10]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
print('Assessing percentage of the first 100 images in dog_files having a detected human face...')    
%time dog_results = assessHumanFaces(dog_files_short) 
print("human faces detected: {} %".format(np.sum(dog_results)))
<<<<<<< HEAD
Assessing percentage of the first 100 images in dog_files having a detected human face...
CPU times: user 54.7 s, sys: 78.9 ms, total: 54.7 s
Wall time: 14.8 s
=======

Assessing percentage of the first 100 images in dog_files having a detected human face...
CPU times: user 51.5 s, sys: 66.5 ms, total: 51.5 s
Wall time: 14 s
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
human faces detected: 11.0 %
<<<<<<< HEAD
In [12]:
=======
In [11]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# plot first 5 dogs detected with human faces
print('human face detected in {} pictures:'.format(int(len(dog_results) - np.sum(dog_results))))

n_max_plots = 5
n_plots = 0
for i, hm in enumerate(dog_results):
    if not hm:
        n_plots += 1
        if n_plots <= n_max_plots:
            if n_plots == 1:
                plt.figure(figsize=(20,5))
            plt.subplot(1, 5, n_plots)
            img = cv2.imread(dog_files_short[i])
            cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            plt.imshow(cv_rgb)
            plt.title(dog_files_short[i].split(os.sep)[1])
        else:
            break

plt.show()   
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
human face detected in 89 pictures:
<<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

No, in my opinion, it is not a reasonable to expect the user to provide a clear view of a face. We could instead add in the training dataset pictures not showing a clearly presented face and/or apply picture augmentation.

<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [10]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
<<<<<<< HEAD

Face detection with PCA

principles of face recognition with PCA

sklearn face recognition example

Accuracy on human face recognition : 99%

=======

Face detection with PCA

source

>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [245]:
=======
In [12]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# gather the training data set in a matrix:
#  - resize the pictures 128x128
#  - convert to gray scale
#  - reshape to vector

def treat_image(img_file):
    """
    This function reads an image, resize it 128x128 and color it to gray scale color
    """
    img = cv2.imread(img_file)
    img = cv2.resize(img, (128,128))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    
    return img

print("preparing training dataset...")
<<<<<<< HEAD

print("adding human faces pictures...")
# take the 101th to 1100th pictures to build the dataset
# the first 100 pictures are left for for validation


sample = []
for i, hf in enumerate(human_files[101:1101]): # let's take the 101th to 200th images fore the training dataset
=======
sample = []
for hf in human_files[100:200]: # let's take the 101th to 200th images fore the training dataset
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    img = treat_image(hf)
    #plt.imshow(img, cmap='gray')
    #plt.show()
    sample.append(img.reshape(img.shape[0]*img.shape[1]))
<<<<<<< HEAD

df_humans = pd.DataFrame(sample)
df_humans['isHuman'] = 1
=======
    
df = pd.DataFrame(sample)    
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
print('done: {} human faces read'.format(df.shape[0]))
<<<<<<< HEAD
preparing training dataset...
adding human faces pictures...
done: 1000 human faces read
=======

preparing training dataset...
done: 100 human faces read
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [246]:
print("Adding dogs pictures")
# take the 101th to 1100th dogs pictures from the Train dataset to build the new training dataset
# the first 100 dogs pictures are left for for validation

sample = []
for i, dg in enumerate(train_files[101:1101]): # let's take the 101th to 200th images fore the training dataset
    img = treat_image(dg)
    #plt.imshow(img, cmap='gray')
    #plt.show()
    sample.append(img.reshape(img.shape[0]*img.shape[1]))
    
df_dogs = pd.DataFrame(sample)
df_dogs['isHuman'] = 0

print('{} dogs  samples read'.format(df_dogs.shape[0]))   
=======
In [13]:
# compute the average face:

average_face_df = df.mean()
average_face_img = average_face_df.as_matrix().reshape(128, 128)
plt.imshow(average_face_img, cmap='gray')
plt.title('average face')
plt.show()

# normalize the training faces
df_train = df - average_face_df
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
Adding dogs pictures
1000 dogs  samples read
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [247]:
#shuffle merged table, split training/testing datasets

print("gather data in dataframe, create label and apply PCA transformation...")
df_merged = shuffle(pd.concat([df_humans, df_dogs], ignore_index=True))
y = df_merged['isHuman']
df_merged.drop('isHuman', axis=1, inplace=True)

print("train/test split...")
X_train, X_test, y_train, y_test = train_test_split(df_merged, y, test_size=0.2)

print("{} samples in the training set.".format(X_train.shape[0]))
print("{} samples in the testing set.".format(X_test.shape[0]))
=======
In [14]:
print('Fitting PCA...')
PCA = PCA(n_components=10)
%time PCA.fit(df_train)
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
gather data in dataframe, create label and apply PCA transformation...
train/test split...
1600 samples in the training set.
400 samples in the testing set.
=======

Fitting PCA...
CPU times: user 128 ms, sys: 221 ms, total: 349 ms
Wall time: 101 ms
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD =======
Out[14]:
PCA(copy=True, iterated_power='auto', n_components=10, random_state=None,
  svd_solver='auto', tol=0.0, whiten=False)
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [248]:
# fit PCA model on human pictures only
#from sklearn.decomposition import PCA

print('Fitting the PCA on human dataset...')
pca = PCA(n_components=150, svd_solver='randomized', whiten=True)
%time pca.fit(df_humans.drop('isHuman', axis=1))

print('transforming Train/test features')
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)

print('Done.')
=======
In [15]:
# plot principal components
plt.figure(figsize=(20,10))
for i, pc in enumerate(PCA.components_):
    plt.subplot(2, 5, i+1)
    plt.imshow(pc.reshape(128, 128), cmap='gray')
    plt.title('Component {}'.format(i+1))
    
plt.show()
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
Fitting the PCA on human dataset...
Wall time: 2.5 s
transforming Train/test features
Done.
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [254]:
# train a SVM binary classifier to predict if a picture contains a human face
# code inspired from http://scikit-learn.org/stable/auto_examples/applications/plot_face_recognition.html#sphx-glr-auto-examples-applications-plot-face-recognition-py

# from sklearn.svm import SVC
# from sklearn.model_selection import GridSearchCV
# from time import time

print("Fitting the classifier to the training set")
t0 = time()
param_grid = {'C': [1e3, 5e3, 1e4, 5e4, 1e5],
              'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], }
clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid)
clf = clf.fit(X_train_pca, y_train)
print("done in %0.3fs" % (time() - t0))
print("Best estimator found by grid search:")
print(clf.best_estimator_)

print('best estimator accuracy: {}'.format(clf.best_estimator_.score(X_test_pca, y_test)))

svc = clf.best_estimator_
=======
In [16]:
# take a new picture

test_img = treat_image(human_files_short[0])
plt.imshow(test_img, cmap='gray')
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
Fitting the classifier to the training set
done in 28.030s
Best estimator found by grid search:
SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.005, kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
best estimator accuracy: 0.9675
In [255]:
def assessHumanFaces_PCA_SVC(img_paths):
    """
    This function loop over a list of picture files and predict if it contains a human face
    The function append "1" to the returned scores list if True, 0 otherwise
    """
    
    print('Assessing human faces in {} images...'.format(len(img_paths)))
    scores = []
    for img_path in img_paths:
        img = treat_image(img_path)
        img_pca =  pca.transform(img.reshape(-1, np.product(img.shape)))
        scores.append(svc.predict(img_pca)[0])
    
    return scores
=======
Out[16]:
<matplotlib.image.AxesImage at 0x7f15c01ab6d8>
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [257]:
%time scores = assessHumanFaces_PCA_SVC(human_files_short)
acc = 100. * np.sum(scores)/len(scores)
print('human face recognition accuracy: {:.2f}%'.format(acc))

# print pictures with no human face recognized
[show_image(hf) for hf, score in zip(human_files_short, scores) if score == 0]
=======
In [17]:
# vectorize the test image and normalize
test_img_df = pd.DataFrame(test_img.reshape(test_img.shape[0]*test_img.shape[1])).transpose()
test_img_df = test_img_df - average_face_df

# apply PCA
test_img_pca = PCA.transform(test_img_df)
test_img_pca

# ... and now?
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
Assessing human faces in 100 images...
Wall time: 1.91 s
human face recognition accuracy: 99.00%
Out[257]:
=======
Out[17]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
[None]
=======
array([[-2571.90983211,   611.80438192,  -152.16933692,   -61.18448483,
        -1221.13925204,  1321.04877066,   225.75457993,  -992.67101714,
          -68.52004837,   874.97639743]])
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

<<<<<<< HEAD
In [20]:
=======
In [18]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
<<<<<<< HEAD
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 8s 0us/step
=======

Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 1s 0us/step
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

<<<<<<< HEAD $$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

=======

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [24]:
def path_to_tensor(img_path):
=======
In [27]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
<<<<<<< HEAD
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm_notebook(img_paths)]
=======
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    return np.vstack(list_of_tensors)
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

<<<<<<< HEAD
In [25]:
# from keras.applications.resnet50 import preprocess_input, decode_predictions
=======
In [20]:
from keras.applications.resnet50 import preprocess_input, decode_predictions
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

<<<<<<< HEAD
In [26]:
=======
In [21]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

<<<<<<< HEAD
In [27]:
=======
In [24]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

score = 0
<<<<<<< HEAD
for hf in tqdm_notebook(human_files_short):
=======
for hf in human_files_short:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    if dog_detector(hf):
        score += 1

print("percentage of the images in human_files_short having a detected dog: {}%".format(score))
<<<<<<< HEAD
percentage of the images in human_files_short having a detected dog: 1%
=======

percentage of the images in human_files_short having a detected dog: 1%
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [28]:
score = 0
for df in tqdm_notebook(dog_files_short):
=======
In [25]:
score = 0
for df in dog_files_short:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    if dog_detector(df):
        score += 1

print("percentage of the images in dog_files_short having a detected dog: {}%".format(score))
<<<<<<< HEAD
percentage of the images in dog_files_short having a detected dog: 100%
=======

percentage of the images in dog_files_short having a detected dog: 100%
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

<<<<<<< HEAD
In [30]:
# from PIL import ImageFile                            
=======
In [28]:
from PIL import ImageFile                            
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
<<<<<<< HEAD


=======

 13%|█▎        | 843/6680 [00:09<01:03, 92.27it/s] 
2002/|/ 30%|| 2002/6680 [00:40<01:33, 50.00it/s]
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======

100%|██████████| 6680/6680 [01:14<00:00, 90.24it/s] 
100%|██████████| 835/835 [00:08<00:00, 100.39it/s]
100%|██████████| 836/836 [00:09<00:00, 85.67it/s] 
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

<<<<<<< HEAD =======

The idea behind the following architecture is to use 3 convolutional layers increasing the amount of filters (16 to 64) while the dimension of the picture decreases with the MaxPooling layer. Each convolutional layer is followed by a drop out layer of 25% in order to mitigate the overfitting. Finally, a global average pooling layer preceed the fully connected output layer of 133 units charachterized by its softmax activation.

This architecture is a simplification of "classical" CNN such as VGGnet which have the demonstrated capability to capture pattern of levels increasing with the amount of layer (first layers detect basic patterns such as stripes or lines while deeper layer are able to capture higher level concepts such as nose, eyes...)

>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
In [32]:
#from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
#from keras.layers import Dropout, Flatten, Dense
#from keras.models import Sequential
=======
In [31]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

print("tensors shape: {}".format(train_tensors.shape))
print("Number of breeds known: {}".format(268-151))

# mark I
model = Sequential()

model.add(Conv2D(16, (3,3), padding='same', activation='relu', input_shape=train_tensors.shape[1:]))
#model.add(Conv2D(16, (3,3), padding='same', activation='relu'))
# 16 2x2 filters, no padding, input shape is 224 x 224
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(32, (3,3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3,3), padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

model.add(GlobalAveragePooling2D())
#model.add(Flatten())

#model.add(Dense(128, activation ='relu'))
#model.add(Dropout(.5))
model.add(Dense(133, activation ='softmax'))

model.summary()
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
tensors shape: (6680, 224, 224, 3)
Number of breeds known: 117
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 16)      448       
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 32)      4640      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 64)        18496     
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 28, 28, 64)        0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 64)                0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               8645      
=================================================================
Total params: 32,229
Trainable params: 32,229
Non-trainable params: 0
_________________________________________________________________
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Compile the Model

<<<<<<< HEAD
In [33]:
=======
In [32]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

<<<<<<< HEAD
In [35]:
#from keras.callbacks import ModelCheckpoint  
=======
In [33]:
from keras.callbacks import ModelCheckpoint  
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 10

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
<<<<<<< HEAD
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8791 - acc: 0.0098Epoch 00001: val_loss improved from inf to 4.85589, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.8788 - acc: 0.0097 - val_loss: 4.8559 - val_acc: 0.0180
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8237 - acc: 0.0144Epoch 00002: val_loss improved from 4.85589 to 4.81058, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.8237 - acc: 0.0144 - val_loss: 4.8106 - val_acc: 0.0156
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7899 - acc: 0.0185Epoch 00003: val_loss improved from 4.81058 to 4.78735, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7902 - acc: 0.0184 - val_loss: 4.7874 - val_acc: 0.0180
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7669 - acc: 0.0170Epoch 00004: val_loss improved from 4.78735 to 4.76469, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7667 - acc: 0.0169 - val_loss: 4.7647 - val_acc: 0.0204
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7435 - acc: 0.0222Epoch 00005: val_loss improved from 4.76469 to 4.75038, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7438 - acc: 0.0222 - val_loss: 4.7504 - val_acc: 0.0240
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7142 - acc: 0.0269Epoch 00006: val_loss improved from 4.75038 to 4.74253, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7142 - acc: 0.0268 - val_loss: 4.7425 - val_acc: 0.0299
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6890 - acc: 0.0278Epoch 00007: val_loss improved from 4.74253 to 4.70387, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6891 - acc: 0.0278 - val_loss: 4.7039 - val_acc: 0.0251
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6569 - acc: 0.0341Epoch 00008: val_loss improved from 4.70387 to 4.66841, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6569 - acc: 0.0341 - val_loss: 4.6684 - val_acc: 0.0240
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6141 - acc: 0.0354Epoch 00009: val_loss improved from 4.66841 to 4.63908, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6139 - acc: 0.0355 - val_loss: 4.6391 - val_acc: 0.0275
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.5757 - acc: 0.0408Epoch 00010: val_loss improved from 4.63908 to 4.62664, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.5747 - acc: 0.0410 - val_loss: 4.6266 - val_acc: 0.0275
=======

Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8837 - acc: 0.0084Epoch 00001: val_loss improved from inf to 4.87549, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 25s 4ms/step - loss: 4.8838 - acc: 0.0084 - val_loss: 4.8755 - val_acc: 0.0144
Epoch 2/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8610 - acc: 0.0131Epoch 00002: val_loss improved from 4.87549 to 4.86373, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.8611 - acc: 0.0130 - val_loss: 4.8637 - val_acc: 0.0132
Epoch 3/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8304 - acc: 0.0162Epoch 00003: val_loss improved from 4.86373 to 4.83335, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.8305 - acc: 0.0162 - val_loss: 4.8334 - val_acc: 0.0156
Epoch 4/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.8020 - acc: 0.0180Epoch 00004: val_loss improved from 4.83335 to 4.79728, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.8017 - acc: 0.0181 - val_loss: 4.7973 - val_acc: 0.0192
Epoch 5/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7678 - acc: 0.0192Epoch 00005: val_loss improved from 4.79728 to 4.76532, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7673 - acc: 0.0192 - val_loss: 4.7653 - val_acc: 0.0204
Epoch 6/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7383 - acc: 0.0219Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7379 - acc: 0.0222 - val_loss: 4.7839 - val_acc: 0.0216
Epoch 7/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.7099 - acc: 0.0249Epoch 00007: val_loss improved from 4.76532 to 4.74480, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.7095 - acc: 0.0250 - val_loss: 4.7448 - val_acc: 0.0240
Epoch 8/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6841 - acc: 0.0269Epoch 00008: val_loss improved from 4.74480 to 4.69970, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6840 - acc: 0.0268 - val_loss: 4.6997 - val_acc: 0.0192
Epoch 9/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6586 - acc: 0.0354Epoch 00009: val_loss improved from 4.69970 to 4.67945, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6583 - acc: 0.0355 - val_loss: 4.6795 - val_acc: 0.0263
Epoch 10/10
6660/6680 [============================>.] - ETA: 0s - loss: 4.6247 - acc: 0.0357Epoch 00010: val_loss improved from 4.67945 to 4.64938, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 24s 4ms/step - loss: 4.6241 - acc: 0.0359 - val_loss: 4.6494 - val_acc: 0.0323
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
Out[35]:
=======
Out[33]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
<keras.callbacks.History at 0x7f9e6c71f908>
=======
<keras.callbacks.History at 0x7fea980367b8>
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Load the Model with the Best Validation Loss

<<<<<<< HEAD
In [36]:
=======
In [34]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

<<<<<<< HEAD
In [37]:
=======
In [35]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
<<<<<<< HEAD
Test accuracy: 2.9904%
=======

Test accuracy: 4.4258%
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

<<<<<<< HEAD
In [38]:
=======
In [36]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
<<<<<<< HEAD
In [39]:
=======
In [37]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
train_VGG16.shape
<<<<<<< HEAD
Out[39]:
=======
Out[37]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
(6680, 7, 7, 512)
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

<<<<<<< HEAD
In [40]:
=======
In [38]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Compile the Model

<<<<<<< HEAD
In [41]:
=======
In [39]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Train the Model

<<<<<<< HEAD
In [42]:
=======
In [40]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
<<<<<<< HEAD
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6620/6680 [============================>.] - ETA: 0s - loss: 12.1322 - acc: 0.1322Epoch 00001: val_loss improved from inf to 10.42250, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 293us/step - loss: 12.1089 - acc: 0.1334 - val_loss: 10.4225 - val_acc: 0.2263
Epoch 2/20
6460/6680 [============================>.] - ETA: 0s - loss: 9.6720 - acc: 0.2998Epoch 00002: val_loss improved from 10.42250 to 9.31309, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 9.6662 - acc: 0.3010 - val_loss: 9.3131 - val_acc: 0.3257
Epoch 3/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.9974 - acc: 0.3758Epoch 00003: val_loss improved from 9.31309 to 9.23963, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 9.0033 - acc: 0.3756 - val_loss: 9.2396 - val_acc: 0.3449
Epoch 4/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.7565 - acc: 0.4106Epoch 00004: val_loss improved from 9.23963 to 9.15356, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 238us/step - loss: 8.7978 - acc: 0.4085 - val_loss: 9.1536 - val_acc: 0.3497
Epoch 5/20
6500/6680 [============================>.] - ETA: 0s - loss: 8.6712 - acc: 0.4332Epoch 00005: val_loss improved from 9.15356 to 9.07586, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 237us/step - loss: 8.6884 - acc: 0.4317 - val_loss: 9.0759 - val_acc: 0.3569
Epoch 6/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.6237 - acc: 0.4409Epoch 00006: val_loss improved from 9.07586 to 8.96773, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 8.6149 - acc: 0.4406 - val_loss: 8.9677 - val_acc: 0.3725
Epoch 7/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.4990 - acc: 0.4551Epoch 00007: val_loss improved from 8.96773 to 8.88949, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 8.4896 - acc: 0.4557 - val_loss: 8.8895 - val_acc: 0.3856
Epoch 8/20
6440/6680 [===========================>..] - ETA: 0s - loss: 8.4238 - acc: 0.4627Epoch 00008: val_loss improved from 8.88949 to 8.82398, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 8.4296 - acc: 0.4624 - val_loss: 8.8240 - val_acc: 0.3749
Epoch 9/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.2537 - acc: 0.4711Epoch 00009: val_loss improved from 8.82398 to 8.57937, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 8.2421 - acc: 0.4720 - val_loss: 8.5794 - val_acc: 0.4024
Epoch 10/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.1406 - acc: 0.4815Epoch 00010: val_loss improved from 8.57937 to 8.54630, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 8.1611 - acc: 0.4799 - val_loss: 8.5463 - val_acc: 0.3940
Epoch 11/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.9986 - acc: 0.4853Epoch 00011: val_loss improved from 8.54630 to 8.43018, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 7.9645 - acc: 0.4868 - val_loss: 8.4302 - val_acc: 0.4072
Epoch 12/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.8436 - acc: 0.5014Epoch 00012: val_loss improved from 8.43018 to 8.30332, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 7.8472 - acc: 0.5012 - val_loss: 8.3033 - val_acc: 0.4168
Epoch 13/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.8056 - acc: 0.5073Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 238us/step - loss: 7.8149 - acc: 0.5064 - val_loss: 8.3456 - val_acc: 0.4216
Epoch 14/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.7626 - acc: 0.5108Epoch 00014: val_loss improved from 8.30332 to 8.25608, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 237us/step - loss: 7.7770 - acc: 0.5099 - val_loss: 8.2561 - val_acc: 0.4180
Epoch 15/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.7040 - acc: 0.5126Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 236us/step - loss: 7.7176 - acc: 0.5117 - val_loss: 8.2976 - val_acc: 0.4144
Epoch 16/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.6792 - acc: 0.5160Epoch 00016: val_loss improved from 8.25608 to 8.23459, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 240us/step - loss: 7.6667 - acc: 0.5162 - val_loss: 8.2346 - val_acc: 0.4192
Epoch 17/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.5633 - acc: 0.5211Epoch 00017: val_loss improved from 8.23459 to 8.17437, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 7.5659 - acc: 0.5210 - val_loss: 8.1744 - val_acc: 0.4204
Epoch 18/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.4690 - acc: 0.5279Epoch 00018: val_loss improved from 8.17437 to 8.06359, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 239us/step - loss: 7.4541 - acc: 0.5286 - val_loss: 8.0636 - val_acc: 0.4287
Epoch 19/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.3243 - acc: 0.5334Epoch 00019: val_loss improved from 8.06359 to 7.84123, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 238us/step - loss: 7.3298 - acc: 0.5329 - val_loss: 7.8412 - val_acc: 0.4419
Epoch 20/20
6500/6680 [============================>.] - ETA: 0s - loss: 7.2324 - acc: 0.5449Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 238us/step - loss: 7.2402 - acc: 0.5445 - val_loss: 7.9161 - val_acc: 0.4395
=======

Train on 6680 samples, validate on 835 samples
Epoch 1/20
6540/6680 [============================>.] - ETA: 0s - loss: 11.6705 - acc: 0.1312Epoch 00001: val_loss improved from inf to 9.56471, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 297us/step - loss: 11.6275 - acc: 0.1343 - val_loss: 9.5647 - val_acc: 0.2575
Epoch 2/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.9708 - acc: 0.3384Epoch 00002: val_loss improved from 9.56471 to 8.78408, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 8.9870 - acc: 0.3376 - val_loss: 8.7841 - val_acc: 0.3401
Epoch 3/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.3304 - acc: 0.4074Epoch 00003: val_loss improved from 8.78408 to 8.41238, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 8.3178 - acc: 0.4082 - val_loss: 8.4124 - val_acc: 0.3940
Epoch 4/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.0741 - acc: 0.4497Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s 240us/step - loss: 8.0916 - acc: 0.4488 - val_loss: 8.4486 - val_acc: 0.3844
Epoch 5/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.9139 - acc: 0.4719Epoch 00005: val_loss improved from 8.41238 to 8.30368, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 7.8896 - acc: 0.4737 - val_loss: 8.3037 - val_acc: 0.4096
Epoch 6/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.8086 - acc: 0.4835Epoch 00006: val_loss improved from 8.30368 to 8.21049, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 7.7941 - acc: 0.4846 - val_loss: 8.2105 - val_acc: 0.4156
Epoch 7/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.7028 - acc: 0.4983Epoch 00007: val_loss improved from 8.21049 to 8.16607, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 7.6904 - acc: 0.4993 - val_loss: 8.1661 - val_acc: 0.4275
Epoch 8/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.5865 - acc: 0.5060Epoch 00008: val_loss improved from 8.16607 to 8.11213, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 7.5765 - acc: 0.5066 - val_loss: 8.1121 - val_acc: 0.4323
Epoch 9/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.5246 - acc: 0.5172Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s 241us/step - loss: 7.5035 - acc: 0.5180 - val_loss: 8.1162 - val_acc: 0.4204
Epoch 10/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.4885 - acc: 0.5237Epoch 00010: val_loss improved from 8.11213 to 8.01970, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 7.4782 - acc: 0.5246 - val_loss: 8.0197 - val_acc: 0.4383
Epoch 11/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.4429 - acc: 0.5269Epoch 00011: val_loss improved from 8.01970 to 8.00426, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 7.4460 - acc: 0.5265 - val_loss: 8.0043 - val_acc: 0.4443
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.3212 - acc: 0.5324Epoch 00012: val_loss improved from 8.00426 to 7.92707, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 7.3283 - acc: 0.5320 - val_loss: 7.9271 - val_acc: 0.4467
Epoch 13/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.1855 - acc: 0.5365Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 240us/step - loss: 7.1847 - acc: 0.5361 - val_loss: 7.9395 - val_acc: 0.4347
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.0635 - acc: 0.5476Epoch 00014: val_loss improved from 7.92707 to 7.78065, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 7.0643 - acc: 0.5475 - val_loss: 7.7807 - val_acc: 0.4407
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 6.9824 - acc: 0.5480Epoch 00015: val_loss improved from 7.78065 to 7.72855, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 6.9753 - acc: 0.5487 - val_loss: 7.7285 - val_acc: 0.4587
Epoch 16/20
6660/6680 [============================>.] - ETA: 0s - loss: 6.8788 - acc: 0.5596Epoch 00016: val_loss improved from 7.72855 to 7.63430, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 6.8872 - acc: 0.5591 - val_loss: 7.6343 - val_acc: 0.4623
Epoch 17/20
6460/6680 [============================>.] - ETA: 0s - loss: 6.8284 - acc: 0.5642Epoch 00017: val_loss improved from 7.63430 to 7.61174, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 6.8408 - acc: 0.5633 - val_loss: 7.6117 - val_acc: 0.4551
Epoch 18/20
6480/6680 [============================>.] - ETA: 0s - loss: 6.7300 - acc: 0.5679Epoch 00018: val_loss improved from 7.61174 to 7.57466, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 241us/step - loss: 6.7344 - acc: 0.5678 - val_loss: 7.5747 - val_acc: 0.4635
Epoch 19/20
6640/6680 [============================>.] - ETA: 0s - loss: 6.6811 - acc: 0.5748Epoch 00019: val_loss improved from 7.57466 to 7.56006, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 6.6705 - acc: 0.5754 - val_loss: 7.5601 - val_acc: 0.4731
Epoch 20/20
6460/6680 [============================>.] - ETA: 0s - loss: 6.6231 - acc: 0.5800Epoch 00020: val_loss improved from 7.56006 to 7.52460, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 6.6286 - acc: 0.5798 - val_loss: 7.5246 - val_acc: 0.4695
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
Out[42]:
=======
Out[40]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
<keras.callbacks.History at 0x7f9e6c113630>
=======
<keras.callbacks.History at 0x7fea8029e7f0>
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Load the Model with the Best Validation Loss

<<<<<<< HEAD
In [43]:
=======
In [41]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

<<<<<<< HEAD
In [44]:
=======
In [42]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
<<<<<<< HEAD
Test accuracy: 44.4976%
=======

Test accuracy: 48.8038%
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Predict Dog Breed with the Model

<<<<<<< HEAD
In [45]:
=======
In [43]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
<<<<<<< HEAD
In [49]:
=======
In [33]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
# define bootleneck feature, download if needed

<<<<<<< HEAD
#import urllib.request
=======
import urllib.request
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

#modelname = 'VGG19'
#modelname = 'Resnet50'
#modelname = 'InceptionV3'
modelname = 'Xception'

url = 'https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/Dog{}Data.npz'.format(modelname)
file_name = os.path.join('bottleneck_features', url.rsplit(os.sep, 1)[-1])

if not os.path.isfile(file_name):
    print('downloading {} bottleneck features...'.format(modelname))
    urllib.request.urlretrieve(url, file_name)
    print('done')
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
downloading Xception bottleneck features...
done
<<<<<<< HEAD
In [50]:
=======
In [34]:
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
### Load bootleneck features

bottleneck_features = np.load(file_name)
train = bottleneck_features['train']
valid = bottleneck_features['valid']
test = bottleneck_features['test']
<<<<<<< HEAD
=======
>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

<<<<<<< HEAD

Step 4 shows us that the Learning Training significantly improve the accuracy of the model. The reason behind is that the base model (in this previous case VGG16) is much more complex has been intensively trained. The early layers of those models are then highly capable to identify basic patterns such as stripes, simple shapes, dots. The specificity level of those patterns then increase whiththe deepness of the next layers. In that sense, the base modle is much better performing in recognizing basic patterns which are common to any images. The added GAP and Dense layers are here used to re-specify the new model to our dog breed classification task.

As such, the following architecture and the training procedure is equivalent to the VGG16 Learning Transfer approach performed in step 4. Each available base model has been tested, and provide the following results:

=======

The architecture and the training procedure is equivalent to the VGG16 Learning Transfer approach. I testedeach available pre-trained model and compared the test accuracies:

>>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
  • VGG19: 49.7608%
  • ResNet50: 78.8278%
  • InceptionV3: 80.5024%
  • <<<<<<< HEAD
  • Xception: 85.1675%

The Learning Transfer from the Xception model give a test accuracy of 84.0909%, significantly higher than the targeted 60%.

=======
  • Xception: 83.7321%
  • The Learning Transfer from the Xception model givethe best test accuracy = 83.7321%, which is significantly over the targeted 60%.

    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    In [51]:
    =======
    In [37]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Define your architecture.
    
    model = Sequential()
    model.add(GlobalAveragePooling2D(input_shape=train.shape[1:]))
    model.add(Dense(133, activation='softmax'))
    
    model.summary()
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    <<<<<<< HEAD
    global_average_pooling2d_3 ( (None, 2048)              0         
    _________________________________________________________________
    dense_3 (Dense)              (None, 133)               272517    
    =======
    global_average_pooling2d_1 ( (None, 2048)              0         
    _________________________________________________________________
    dense_1 (Dense)              (None, 133)               272517    
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    =================================================================
    Total params: 272,517
    Trainable params: 272,517
    Non-trainable params: 0
    _________________________________________________________________
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    (IMPLEMENTATION) Compile the Model

    <<<<<<< HEAD
    In [52]:
    =======
    In [38]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Compile the model.
    
    model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    (IMPLEMENTATION) Train the Model

    Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

    You are welcome to augment the training data, but this is not a requirement.

    <<<<<<< HEAD
    In [74]:
    =======
    In [39]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Train the model.
    
    checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.{}.hdf5'.format(modelname), 
                                   verbose=1, save_best_only=True)
    
    model.fit(train, train_targets, 
              validation_data=(valid, valid_targets),
              epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
    
    <<<<<<< HEAD
    Train on 6680 samples, validate on 835 samples
    Epoch 1/20
    6620/6680 [============================>.] - ETA: 0s - loss: 1.0626 - acc: 0.7344Epoch 00001: val_loss improved from inf to 0.52759, saving model to saved_models/weights.best.Xception.hdf5
    6680/6680 [==============================] - 3s 422us/step - loss: 1.0579 - acc: 0.7349 - val_loss: 0.5276 - val_acc: 0.8395
    Epoch 2/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.3943 - acc: 0.8758Epoch 00002: val_loss improved from 0.52759 to 0.49128, saving model to saved_models/weights.best.Xception.hdf5
    6680/6680 [==============================] - 3s 390us/step - loss: 0.3939 - acc: 0.8756 - val_loss: 0.4913 - val_acc: 0.8479
    Epoch 3/20
    6640/6680 [============================>.] - ETA: 0s - loss: 0.3221 - acc: 0.8988Epoch 00003: val_loss did not improve
    6680/6680 [==============================] - 3s 385us/step - loss: 0.3220 - acc: 0.8988 - val_loss: 0.4982 - val_acc: 0.8599
    Epoch 4/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.2811 - acc: 0.9151Epoch 00004: val_loss did not improve
    6680/6680 [==============================] - 3s 382us/step - loss: 0.2802 - acc: 0.9151 - val_loss: 0.4920 - val_acc: 0.8479
    Epoch 5/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.2411 - acc: 0.9258Epoch 00005: val_loss did not improve
    6680/6680 [==============================] - 3s 379us/step - loss: 0.2425 - acc: 0.9251 - val_loss: 0.5003 - val_acc: 0.8575
    Epoch 6/20
    6640/6680 [============================>.] - ETA: 0s - loss: 0.2163 - acc: 0.9340Epoch 00006: val_loss did not improve
    6680/6680 [==============================] - 3s 388us/step - loss: 0.2164 - acc: 0.9341 - val_loss: 0.5498 - val_acc: 0.8491
    Epoch 7/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.1887 - acc: 0.9387Epoch 00007: val_loss did not improve
    6680/6680 [==============================] - 3s 398us/step - loss: 0.1909 - acc: 0.9383 - val_loss: 0.5490 - val_acc: 0.8515
    Epoch 8/20
    6600/6680 [============================>.] - ETA: 0s - loss: 0.1746 - acc: 0.9465Epoch 00008: val_loss did not improve
    6680/6680 [==============================] - 3s 394us/step - loss: 0.1762 - acc: 0.9464 - val_loss: 0.5449 - val_acc: 0.8539
    Epoch 9/20
    6600/6680 [============================>.] - ETA: 0s - loss: 0.1618 - acc: 0.9491Epoch 00009: val_loss did not improve
    6680/6680 [==============================] - 3s 396us/step - loss: 0.1619 - acc: 0.9491 - val_loss: 0.5849 - val_acc: 0.8575
    Epoch 10/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.1457 - acc: 0.9571Epoch 00010: val_loss did not improve
    6680/6680 [==============================] - 3s 387us/step - loss: 0.1460 - acc: 0.9564 - val_loss: 0.5981 - val_acc: 0.8599
    Epoch 11/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.1347 - acc: 0.9593Epoch 00011: val_loss did not improve
    6680/6680 [==============================] - 2s 363us/step - loss: 0.1356 - acc: 0.9591 - val_loss: 0.5665 - val_acc: 0.8647
    Epoch 12/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.1215 - acc: 0.9606Epoch 00012: val_loss did not improve
    6680/6680 [==============================] - 2s 361us/step - loss: 0.1213 - acc: 0.9606 - val_loss: 0.5873 - val_acc: 0.8611
    Epoch 13/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.1151 - acc: 0.9628Epoch 00013: val_loss did not improve
    6680/6680 [==============================] - 2s 365us/step - loss: 0.1138 - acc: 0.9632 - val_loss: 0.6054 - val_acc: 0.8635
    Epoch 14/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.1054 - acc: 0.9681Epoch 00014: val_loss did not improve
    6680/6680 [==============================] - 2s 356us/step - loss: 0.1064 - acc: 0.9681 - val_loss: 0.6081 - val_acc: 0.8623
    Epoch 15/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.0969 - acc: 0.9698Epoch 00015: val_loss did not improve
    6680/6680 [==============================] - 2s 370us/step - loss: 0.0962 - acc: 0.9699 - val_loss: 0.6079 - val_acc: 0.8563
    Epoch 16/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.0901 - acc: 0.9719Epoch 00016: val_loss did not improve
    6680/6680 [==============================] - 3s 378us/step - loss: 0.0904 - acc: 0.9719 - val_loss: 0.6660 - val_acc: 0.8587
    Epoch 17/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.0852 - acc: 0.9757Epoch 00017: val_loss did not improve
    6680/6680 [==============================] - 3s 382us/step - loss: 0.0863 - acc: 0.9753 - val_loss: 0.6859 - val_acc: 0.8479
    Epoch 18/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.0805 - acc: 0.9766Epoch 00018: val_loss did not improve
    6680/6680 [==============================] - 3s 383us/step - loss: 0.0814 - acc: 0.9763 - val_loss: 0.6576 - val_acc: 0.8491
    Epoch 19/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.0770 - acc: 0.9783Epoch 00019: val_loss did not improve
    6680/6680 [==============================] - 3s 388us/step - loss: 0.0771 - acc: 0.9777 - val_loss: 0.6853 - val_acc: 0.8575
    Epoch 20/20
    6600/6680 [============================>.] - ETA: 0s - loss: 0.0723 - acc: 0.9794Epoch 00020: val_loss did not improve
    6680/6680 [==============================] - 3s 391us/step - loss: 0.0721 - acc: 0.9795 - val_loss: 0.6992 - val_acc: 0.8527
    =======
    
    
    Train on 6680 samples, validate on 835 samples
    Epoch 1/20
    6600/6680 [============================>.] - ETA: 0s - loss: 1.0651 - acc: 0.7308Epoch 00001: val_loss improved from inf to 0.49588, saving model to saved_models/weights.best.Xception.hdf5
    6680/6680 [==============================] - 3s 431us/step - loss: 1.0588 - acc: 0.7325 - val_loss: 0.4959 - val_acc: 0.8431
    Epoch 2/20
    6520/6680 [============================>.] - ETA: 0s - loss: 0.3934 - acc: 0.8747Epoch 00002: val_loss did not improve
    6680/6680 [==============================] - 3s 384us/step - loss: 0.3952 - acc: 0.8746 - val_loss: 0.4965 - val_acc: 0.8479
    Epoch 3/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.3184 - acc: 0.9023Epoch 00003: val_loss did not improve
    6680/6680 [==============================] - 3s 385us/step - loss: 0.3207 - acc: 0.9013 - val_loss: 0.5276 - val_acc: 0.8395
    Epoch 4/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.2800 - acc: 0.9135Epoch 00004: val_loss did not improve
    6680/6680 [==============================] - 3s 387us/step - loss: 0.2802 - acc: 0.9132 - val_loss: 0.5063 - val_acc: 0.8575
    Epoch 5/20
    6640/6680 [============================>.] - ETA: 0s - loss: 0.2432 - acc: 0.9233Epoch 00005: val_loss did not improve
    6680/6680 [==============================] - 3s 409us/step - loss: 0.2440 - acc: 0.9232 - val_loss: 0.4982 - val_acc: 0.8587
    Epoch 6/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.2124 - acc: 0.9330Epoch 00006: val_loss did not improve
    6680/6680 [==============================] - 3s 406us/step - loss: 0.2142 - acc: 0.9326 - val_loss: 0.5490 - val_acc: 0.8503
    Epoch 7/20
    6640/6680 [============================>.] - ETA: 0s - loss: 0.1982 - acc: 0.9387Epoch 00007: val_loss did not improve
    6680/6680 [==============================] - 3s 407us/step - loss: 0.1993 - acc: 0.9386 - val_loss: 0.5303 - val_acc: 0.8635
    Epoch 8/20
    6640/6680 [============================>.] - ETA: 0s - loss: 0.1781 - acc: 0.9464Epoch 00008: val_loss did not improve
    6680/6680 [==============================] - 3s 409us/step - loss: 0.1782 - acc: 0.9461 - val_loss: 0.5541 - val_acc: 0.8563
    Epoch 9/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.1625 - acc: 0.9502Epoch 00009: val_loss did not improve
    6680/6680 [==============================] - 3s 406us/step - loss: 0.1615 - acc: 0.9503 - val_loss: 0.5458 - val_acc: 0.8683
    Epoch 10/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.1487 - acc: 0.9564Epoch 00010: val_loss did not improve
    6680/6680 [==============================] - 3s 398us/step - loss: 0.1479 - acc: 0.9564 - val_loss: 0.5673 - val_acc: 0.8551
    Epoch 11/20
    6580/6680 [============================>.] - ETA: 0s - loss: 0.1371 - acc: 0.9587Epoch 00011: val_loss did not improve
    6680/6680 [==============================] - 3s 392us/step - loss: 0.1366 - acc: 0.9585 - val_loss: 0.5664 - val_acc: 0.8563
    Epoch 12/20
    6660/6680 [============================>.] - ETA: 0s - loss: 0.1290 - acc: 0.9617Epoch 00012: val_loss did not improve
    6680/6680 [==============================] - 3s 385us/step - loss: 0.1287 - acc: 0.9618 - val_loss: 0.6275 - val_acc: 0.8515
    Epoch 13/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.1165 - acc: 0.9650Epoch 00013: val_loss did not improve
    6680/6680 [==============================] - 3s 384us/step - loss: 0.1152 - acc: 0.9654 - val_loss: 0.5713 - val_acc: 0.8671
    Epoch 14/20
    6540/6680 [============================>.] - ETA: 0s - loss: 0.1087 - acc: 0.9667Epoch 00014: val_loss did not improve
    6680/6680 [==============================] - 3s 384us/step - loss: 0.1097 - acc: 0.9662 - val_loss: 0.5926 - val_acc: 0.8635
    Epoch 15/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.0978 - acc: 0.9704Epoch 00015: val_loss did not improve
    6680/6680 [==============================] - 3s 384us/step - loss: 0.0969 - acc: 0.9707 - val_loss: 0.6182 - val_acc: 0.8659
    Epoch 16/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.0936 - acc: 0.9733Epoch 00016: val_loss did not improve
    6680/6680 [==============================] - 3s 405us/step - loss: 0.0954 - acc: 0.9735 - val_loss: 0.6454 - val_acc: 0.8623
    Epoch 17/20
    6560/6680 [============================>.] - ETA: 0s - loss: 0.0883 - acc: 0.9741Epoch 00017: val_loss did not improve
    6680/6680 [==============================] - 3s 408us/step - loss: 0.0875 - acc: 0.9743 - val_loss: 0.6417 - val_acc: 0.8587
    Epoch 18/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.0819 - acc: 0.9766Epoch 00018: val_loss did not improve
    6680/6680 [==============================] - 3s 416us/step - loss: 0.0828 - acc: 0.9763 - val_loss: 0.6411 - val_acc: 0.8599
    Epoch 19/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.0780 - acc: 0.9769Epoch 00019: val_loss did not improve
    6680/6680 [==============================] - 3s 413us/step - loss: 0.0776 - acc: 0.9769 - val_loss: 0.6443 - val_acc: 0.8647
    Epoch 20/20
    6620/6680 [============================>.] - ETA: 0s - loss: 0.0763 - acc: 0.9773Epoch 00020: val_loss did not improve
    6680/6680 [==============================] - 3s 414us/step - loss: 0.0759 - acc: 0.9775 - val_loss: 0.6900 - val_acc: 0.8575
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    Out[74]:
    =======
    Out[39]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    <keras.callbacks.History at 0x7f9e6e0c8eb8>
    =======
    <keras.callbacks.History at 0x7f15779db390>
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    (IMPLEMENTATION) Load the Model with the Best Validation Loss

    <<<<<<< HEAD
    In [75]:
    =======
    In [40]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Load the model weights with the best validation loss.
    
    print("Loading {} model with Best Validation Loss".format(modelname))
    model.load_weights('saved_models/weights.best.{}.hdf5'.format(modelname))
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Loading Xception model with Best Validation Loss
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    (IMPLEMENTATION) Test the Model

    Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

    <<<<<<< HEAD
    In [76]:
    =======
    In [41]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Calculate classification accuracy on the test dataset.
    
    # VGG19: 49.7608%
    # ResNet50: 78.8278%
    # InceptionV3: 80.5024%
    <<<<<<< HEAD
    # Xception: 84.0909%
    =======
    # Xception: 83.7321%
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    # get index of predicted dog breed for each image in test set
    predictions = [np.argmax(model.predict(np.expand_dims(feature, axis=0))) for feature in test]
    
    # report test accuracy
    test_accuracy = 100*np.sum(np.array(predictions)==np.argmax(test_targets, axis=1))/len(predictions)
    print('Test accuracy {}: {:.4f}%'.format(modelname, test_accuracy))
    
    <<<<<<< HEAD
    Test accuracy Xception: 84.0909%
    =======
    
    
    Test accuracy Xception: 83.7321%
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    (IMPLEMENTATION) Predict Dog Breed with the Model

    Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

    Similar to the analogous function in Step 5, your function should have three steps:

    1. Extract the bottleneck features corresponding to the chosen CNN model.
    2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
    3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

    The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

    extract_{network}
    
    

    where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

    <<<<<<< HEAD
    In [79]:
    =======
    In [42]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Write a function that takes a path to an image as input
    ### and returns the dog breed that is predicted by the model.
    
    from extract_bottleneck_features import extract_Xception
    
    def predict_breed(img_path):
        """
        This function extract the Xception bottleneck features of an image
        and return the predicted dog breed with model trained in step 5
        """
        
        # extract bottleneck features
        feature = extract_Xception(path_to_tensor(img_path))
        breed_prediction = dog_names[np.argmax(model.predict(feature))]
        return breed_prediction
    <<<<<<< HEAD
    =======
    
    def show_image(img_path, title='default'):
        img = cv2.imread(img_path)
        cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(cv_rgb)
        if title is not None:
            if title == 'default':
                title = img_path.rsplit(os.sep, 1)[-1]
            plt.title(title)
        plt.show()   
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    In [99]:
    =======
    In [44]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    # select a random picture
    img_path = np.random.choice(test_files)
    
    # show the picture
    show_image(img_path)
    
    print("Breed prediction: {}".format(predict_breed(img_path)))
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    <<<<<<< HEAD
    Breed prediction: French_bulldog
    =======
    
    
    Breed prediction: Basenji
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    Step 6: Write your Algorithm

    Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

    • if a dog is detected in the image, return the predicted breed.
    • if a human is detected in the image, return the resembling dog breed.
    • if neither is detected in the image, provide output that indicates an error.

    You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

    Some sample output for our algorithm is provided below, but feel free to design your own user experience!

    Sample Human Output

    (IMPLEMENTATION) Write your Algorithm

    <<<<<<< HEAD
    In [119]:
    =======
    In [45]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ### TODO: Write your algorithm.
    ### Feel free to use as many code cells as needed.
    
    # the detector app  
    def detector(img_path, title='default', isurl=False):
        if isurl:
            file_name = 'images/{}'.format(title)
            urllib.request.urlretrieve(img_path, file_name)
            img_path = file_name
        
        show_image(img_path, title=title)
    
        if face_detector(img_path):
            print("Hello, you look to be a human.")
            print("If you where a dog, you would be a....")
        else:
            if dog_detector(img_path):
                print("Hello, you look to be a dog.")
                print("You are a...")
            else:
                print("Sorry, can't figure out if you are human or a dog")
                return
            
        dog_breed = predict_breed(img_path)
        print(dog_breed)   
    
    <<<<<<< HEAD
    In [90]:
    =======
    In [46]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    # try on a dog
    detector(np.random.choice(test_files))
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    <<<<<<< HEAD
    Hello, you look to be a dog.
    You are a...
    French_bulldog
    =======
    
    
    Hello, you look to be a dog.
    You are a...
    Chow_chow
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    In [92]:
    =======
    In [47]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    # try on a human
    detector(np.random.choice(human_files))
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    <<<<<<< HEAD
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Petit_basset_griffon_vendeen
    =======
    
    
    Hello, you look to be a human.
    If you where a dog, you would be a....
    English_toy_spaniel
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    In [124]:
    detector('lfw/Jose_Dirceu/Jose_Dirceu_0002.jpg')
    =======
    
    In [48]:
    # try on a not recognized face
    detector('lfw/Jose_Dirceu/Jose_Dirceu_0002.jpg')
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Sorry, can't figure out if you are human or a dog
    
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397

    Step 7: Test Your Algorithm

    In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

    (IMPLEMENTATION) Test Your Algorithm on Sample Images!

    Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

    Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

    Answer:

    The output is very satisfying, the app give the right answer most of the time. Failures seems to occure when the head is significantly turned or when there are other objects occulting the face.

    Three ways of improvements could be:

    • augment the training set pictures with rotation,
    • augment the training set pictures with zoom in/out
    • add pictures with occulting objects in the dataset
    <<<<<<< HEAD
    In [120]:
    =======
    In [49]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    ## TODO: Execute your algorithm from Step 6 on
    ## at least 6 images on your computer.
    ## Feel free to use as many code cells as needed.
    
    url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Elon_Musk_2015.jpg/800px-Elon_Musk_2015.jpg'
    detector(url, 'elon', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Dachshund
    
    <<<<<<< HEAD
    In [122]:
    =======
    In [50]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'https://media.licdn.com/dms/image/C4D03AQGmpY3ykcZQBA/profile-displayphoto-shrink_200_200/0?e=1529071200&v=beta&t=prCJThPDM_26jqE3kGnRB88AqL2U-gOX3sFY8CYynB8'
    detector(url, 'me', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Petit_basset_griffon_vendeen
    =======
    
    
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Havanese
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    In [123]:
    =======
    In [51]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'https://media.licdn.com/dms/image/C5603AQEACd7Ea1izig/profile-displayphoto-shrink_800_800/0?e=1529071200&v=beta&t=uK82Mg5zOQNU8M1RZSTTFqA2rwzdnx07SjG6-qMLIZI'
    detector(url, 'dan', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Smooth_fox_terrier
    
    <<<<<<< HEAD
    In [130]:
    =======
    In [52]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url='https://i.ebayimg.com/images/g/cBMAAOSw44BYZGiJ/s-l300.jpg'
    detector(url, 'leia', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Smooth_fox_terrier
    
    <<<<<<< HEAD
    In [131]:
    =======
    In [53]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'https://media.gq.com/photos/580a8e09aafbc05a239a582f/master/pass/Dude.jpg'
    detector(url, 'dude', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Petit_basset_griffon_vendeen
    =======
    
    
    Hello, you look to be a human.
    If you where a dog, you would be a....
    Afghan_hound
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    
    <<<<<<< HEAD
    In [126]:
    =======
    In [54]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'https://rlv.zcache.com/scooby_doo_pose_27_postcard-rb67554b17a1e47b0810ec9c70517a327_vgbaq_8byvr_540.jpg'
    detector(url, 'scoobydoo', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Sorry, can't figure out if you are human or a dog
    
    <<<<<<< HEAD
    In [127]:
    =======
    In [55]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'https://vignette.wikia.nocookie.net/princebalto/images/4/4e/Lassie-cozi-thumb.jpeg/revision/latest?cb=20141024212828'
    detector(url, 'lassie', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Hello, you look to be a dog.
    You are a...
    Collie
    
    <<<<<<< HEAD
    In [128]:
    =======
    In [56]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'https://vignette.wikia.nocookie.net/beethoven-the-dog/images/f/fd/Missy.png/revision/latest/scale-to-width-down/1000?cb=20170814184052'
    detector(url, 'Missy', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    =======
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    Hello, you look to be a dog.
    You are a...
    Pointer
    
    <<<<<<< HEAD
    In [129]:
    =======
    In [ ]:
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    url = 'http://i.dailymail.co.uk/i/pix/2017/07/07/11/421B42C700000578-4674506-image-m-38_1499423111428.jpg'
    detector(url, 'Beethoven', isurl=True)
    
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD ======= >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397
    <<<<<<< HEAD
    Hello, you look to be a dog.
    You are a...
    Saint_bernard
    =======
    
    
    Hello, you look to be a dog.
    You are a...
    >>>>>>> daee7a057efa0c400a426e501ff39a0ad068f397